import React, { useState, useCallback, useContext } from 'react'

import { View, ScrollView } from '@tarojs/components'

import _ from 'underscore'

import { AtSearchBar } from 'taro-ui'

import "taro-ui/dist/style/components/search-bar.scss"
import "taro-ui/dist/style/components/button.scss"
import "taro-ui/dist/style/components/icon.scss"

import miniContext from '../../context/minipet-db.js'

import { SearchWrap } from './styledSearch'

export default function search() {

  let [list, setList] = useState([])
  let [inputShowed, setInputShowed] = useState(false)
  let [inputVal, setInputVal] = useState('')

  let minipet = useContext(miniContext)

  const onChange = _.debounce(useCallback((value) => {
    setInputVal(value)
    let reg = new RegExp(inputVal, 'gi')
    minipet.where({
      message: reg
    })
    .get({
      success: (res) => {
        setList(res.data)
      }
    })
  }, []), 300)

  const handleActionClick = useCallback(() => {
    let reg = new RegExp(inputVal, 'gi')
    minipet.where({
      message: reg
    })
    .get({
      success: (res) => {
        setList(res.data)
      }
    })
  }, [])

  return (
    <SearchWrap>
      <View class="search-box">
        <View class="search-body">
          <View class="input">
          <AtSearchBar
            value={inputVal}
            onChange={onChange}
            onActionClick={handleActionClick}
            showActionButton={true}
          />
          </View>
        </View>
        <ScrollView class="search-list" scroll-y="true">
          {
            list.map((item) => {
              return (
                <View class="list-item">
                  <View class="list-title">
                    {item.address}
                  </View>
                  <View class="list-body">
                    {item.message}
                  </View>
                </View>
              )
            })
          }
        </ScrollView>
      </View>
    </SearchWrap>
  )
}
